/**
 * 授权相关接口
 * @authors 杨兴洲（of2502）
 * @date    2017/3/14 18:14
 * @version 1.0
 */
import {Router} from "express";
import WeixinService from "../../service/weixin-service";
import SiteService from "../../service/site-service";
const router = Router();

/**
 * 获取授权URL
 */
router.get('/url', (req, res, next) => {
    if (!req.query.redirect_uri) {
        const error = new Error();
        error["errcode"] = 10001;
        error["errmsg"] = "缺少参数redirect_uri";
        return next(error);
    }
    next();
}, (req, res, next) => {
    (async () => {
        try {
            const {redirect_uri: redirectUri} = req.query;
            let accessToken = await SiteService.getAccessToken();
            let preAuthCode = await WeixinService.getPreAuthCode({accessToken});
            let url = WeixinService.getAuthUrl({preAuthCode, redirectUri});
            res.status(200).json({url});
        } catch (error) {
            next(error);
        }
    })();
});

export default router;
